package org.eae.eldf.webapp.controller.login;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import org.eae.eldf.webapp.base.AbstractController;
import org.eae.eldf.entity.sys.SysOperator;
import org.eae.eldf.framework.spring.SpringSecurityUtils;
import org.eae.eldf.framework.utils.MD5;
import org.eae.eldf.service.sys.SysOperatorService;


@Controller
public class LoginController extends AbstractController{
	
	private String _loginUserName;
	private String _loginErrorMsg;
	private String request_locale;
	
	private SysOperatorService operatorService;
	
	@Autowired
	public void setOperatorService(SysOperatorService operatorService) {
		this.operatorService = operatorService;
	}

	@RequestMapping("/login.htm")
	public String showloginform(ModelMap model,HttpSession session){
		if (session != null) {
			Object autoerror = session.getAttribute(SpringSecurityUtils.LOGIN_ERROR_AUTHCODE);
			if(null!=autoerror){
				//_loginErrorMsg = this.getText("error.common.login.authcode");
				_loginErrorMsg = "验证码错误";
			}else{
				Object _obj = session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
				if(_obj instanceof AuthenticationException){
					model.addAttribute("_loginErrorMsg", "用户名或密码不正确");
				}
				if (_obj instanceof BadCredentialsException) {
					BadCredentialsException bad = (BadCredentialsException) _obj;
					Authentication token = bad.getAuthentication();
					_loginErrorMsg = bad.getMessage();
					_loginUserName = token.getName();
					SysOperator operator = operatorService.queryByUser(_loginUserName);
					if(operator==null){
						model.addAttribute("_loginErrorMsg", "用户不存在");
					}else{
						if(operator.getBisfreeze()==1){
							model.addAttribute("_loginErrorMsg", "用户已被禁用");
						}else if(!operator.getSpassword().equalsIgnoreCase(MD5.encode(token.getCredentials().toString()))){
							model.addAttribute("_loginErrorMsg", "密码不正确");
						}
					}
					
				}
			}
		}
		
		return "/login";
	}

	public String get_loginUserName() {
		return _loginUserName;
	}

	public void set_loginUserName(String _loginUserName) {
		this._loginUserName = _loginUserName;
	}

	public String get_loginErrorMsg() {
		return _loginErrorMsg;
	}

	public void set_loginErrorMsg(String _loginErrorMsg) {
		this._loginErrorMsg = _loginErrorMsg;
	}

	public String getRequest_locale() {
		return request_locale;
	}

	public void setRequest_locale(String request_locale) {
		this.request_locale = request_locale;
	}
	
	
}
